import React from 'react';
import { history } from 'umi'
import { Row, Col, Button, message, Typography, Modal } from 'antd';
// import { COMMUNICATE_RESULT_ENUM, NOTICE_TYPE } from '@/pages/Recruitment/dictionary';
import { COMMUNICATE_RESULT_ENUM } from '@/pages/Recruitment/dictionary';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { workFlowHireAddData, saveHrCommunicate } from '@/pages/Recruitment/service';
import { useRequest, defaultFormatResult } from '@/hooks';
import pageTabUtil from '@/utils/pageTabUtil';
import styles from './Action.less';

const { Text } = Typography;

/**
 * 导出给录用详细重新发起审批使用
 * @param {Object} params
 * @param {number} params.employId
 * @param {number} params.candidateId
 * @param {number} params.labourPeriodNumber
 * @param {number} params.labourPeriodType
 * @param {number} params.probationMonthSalary
 * @param {number} params.probationPeriodNumber
 * @param {number} params.probationPeriodType
 * @param {string} params.remark
 * @param {string} params.suggestedEntryTime
 * @param {number} params.workType
 * @param {boolean} redirect 是否重定向到其它页面，保存状态下为 false
 */
export const launchApprovalProcess = async ({ params = {}, setFlowLoading = () => {}, callback, redirect = true }) => {
    setFlowLoading(true);
    const { workFlowUrl } = await hasWorkFlowByType('RecruitEmployApply'); // 验证流程是否存在
    if (!workFlowUrl) {
        setFlowLoading(false);
        return;
    }
    const res = await workFlowHireAddData(params);
    const { code, data: flowId, msg } = res;
    if (code !== 10000) {
        message.error(msg);
        setFlowLoading(false);
        return;
    }

    setFlowLoading(false);
    // 提交前要获取hiDataId
    if (callback) {
        const next = await callback(flowId);
        if (!next) return;
    }

    if (redirect) history.push(`${workFlowUrl}${flowId}`);
};

function Action({
    form,
    candidateId,
    employId,
    recruitEmployContactVOList, // 这里面存着录音机的ref，从这里获取录音数据
    isSecond,
    positionCodeChangeFlag,
    reloadAfterSave
}) {
    const { validateFieldsAndScroll } = form;
    const [flowLoading, setFlowLoading] = React.useState(false);
    const [saved, setSaved] = React.useState(false);

    // HR沟通提交
    const { loading: submitLoading, run: runSubmit } = useRequest(saveHrCommunicate, {
        manual: true,
        ...defaultFormatResult
    });

    /**
     * 获取全部录音
     */
    const getAllRecUrl = () =>
        new Promise(resolve => {
            const PromisesArr = [];
            const URLArr = [];
            recruitEmployContactVOList.forEach(item => {
                if (item.id !== undefined) {
                    PromisesArr.push(Promise.resolve({ recordUrl: item.recordUrl }));
                } else {
                    PromisesArr.push(item.recorderRef.current.getRecordInfo());
                }
            });
            Promise.all(PromisesArr).then(resArr => {
                resArr.forEach(item => {
                    URLArr.push(item?.recordUrl ? { recordUrl: item?.recordUrl } : {});
                });
                console.log('URLArr', URLArr);
                resolve(URLArr);
                return URLArr;
            });
        });

    /**
     * 保存沟通到服务器，
     * 在此处拼装服务器需要的数据结构
     */
    const saveCommInfo = async values => {
        // const recordInfo = await recordButtonRef?.current?.getRecordInfo();
        // const recordUrlParam = recordInfo?.recordUrl ? { recordUrl: recordInfo?.recordUrl } : {};
        const payload = {
            ...values,
            candidateId
        };

        const recURLArr = await getAllRecUrl();
        const tempRecruitEmployContactDTOList = []; // 联系记录对应数组
        const tempArr = Object.values(payload.recruitEmployContactDTOList);
        console.log('payload.recruitEmployContactDTOList', tempArr);
        // 格式化form中获取的数据
        for (let index = 0; index < tempArr.length; index += 1) {
            const item = tempArr[index];
            const { contactTime, ...rest } = item;
            tempRecruitEmployContactDTOList.push({
                recordUrl: recURLArr[index]?.recordUrl,
                contactTime: contactTime?.format('YYYY-MM-DD HH:mm:ss'),
                ...rest
            });
        }
        // 针对保存后提交的情况，把暂存后请求来的数据覆盖到form中
        for (let index = 0; index < recruitEmployContactVOList.length; index += 1) {
            const element1 = tempRecruitEmployContactDTOList[index];
            const element2 = recruitEmployContactVOList[index];
            tempRecruitEmployContactDTOList[index] = {
                ...element1,
                ...element2
            };
        }
        payload.recruitEmployContactDTOList = tempRecruitEmployContactDTOList;
        // payload.contactRecordSaveDTO = tempRecruitEmployContactDTOList[tempRecruitEmployContactDTOList.length - 1]; // 这个不用传了，后端处理掉
        console.log('saveCommInfo:');
        console.log(payload);
        const result = await runSubmit(employId, payload);
        return result;
    };

    /**
     * 提交沟通详情
     * @param {*} isWorkFlow  是否发起审批
     * @param {*} isSave 是否为保存（不发起审批）
     */
    const handleSubmit = ({ callback, isWorkFlow = false, isSave = false }) => {
        validateFieldsAndScroll(
            {
                scroll: {
                    offsetBottom: 88
                }
            },
            async (errors, values) => {
                console.log('validateFieldsAndScroll,', values);
                // 前面部分提交到流程审批前置接口
                const { recruitEmployInfoVO, ...rest } = values;

                // 冗余，但是必须？
                const extraParams = {
                    officialMonthSalary: values?.salarySaveDTO?.suggestedMonthSalary,
                    employUrl: values?.salarySaveDTO?.salaryProveUrl
                };

                // return;
                if (!errors) {
                    if (isWorkFlow || isSave) {
                        console.log(`isWorkFlow:${isWorkFlow}isSave:${isSave}`);
                        // 保存当前表单所需参数
                        const extraParamsForProcess = isSave ? { redirect: false } : {}; // 带这个参数，就走保存的逻辑
                        const extraParamsForSave = isSave ? { resultWay: 1 } : {}; // 带这个参数，就走保存的逻辑
                        launchApprovalProcess({
                            setFlowLoading,
                            params: {
                                candidateId,
                                employId,
                                positionCodeChangeFlag,
                                ...extraParams,
                                ...recruitEmployInfoVO,
                                suggestedEntryTime: recruitEmployInfoVO?.suggestedEntryTime?.format(
                                    'YYYY-MM-DD HH:mm:ss'
                                )
                            },
                            // hiDataId --- 流程id
                            callback: async hiDataId => {
                                const result = await saveCommInfo({
                                    hiDataId,
                                    ...extraParamsForSave,
                                    ...rest
                                });
                                if (result && callback) callback();
                                return result;
                            },
                            ...extraParamsForProcess
                        });
                        return;
                    }

                    const result = await saveCommInfo(rest);
                    if (result && callback) callback();
                }
            }
        );
    };
    const routerGo = () => {
        pageTabUtil.goBack();
    };
    const resultType = form.getFieldValue('resultType');

    const handleCancel = () => {
        if (saved) {
            routerGo();
            return;
        }
        Modal.confirm({
            title: '当前页面信息暂未保存，确定离开此页面？',
            cancelText: '取消',
            okText: '确认',
            onOk: () => {
                routerGo();
            }
        });
    };

    const handleSave = () => {
        handleSubmit({
            isSave: true,
            callback: () => {
                reloadAfterSave();
                message.success('保存成功');
                setSaved(true);
            }
        });
    };
    const saveButton = <Button onClick={handleSave}>保存</Button>;

    const renderButton = () => {
        const loading = submitLoading || flowLoading;
        const buttonProps = {
            loading,
            type: 'primary'
        };
        if (resultType === COMMUNICATE_RESULT_ENUM.AGREE) {
            return (
                <div className={styles.buttonWrapper}>
                    <Button onClick={handleCancel}>取消</Button>
                    {saveButton}
                    <Button {...buttonProps} onClick={() => handleSubmit({ isWorkFlow: true })}>
                        发起审批
                    </Button>
                </div>
            );
        }
        if ([COMMUNICATE_RESULT_ENUM.NEGOTIATE, COMMUNICATE_RESULT_ENUM.PREOUT].includes(resultType)) {
            return (
                <div className={styles.buttonWrapper}>
                    <Text className={styles.addMarginRight} disabled>
                        通知用人部门进行薪资确认
                    </Text>
                    <Button onClick={handleCancel}>取消</Button>
                    {saveButton}
                    <Button
                        {...buttonProps}
                        onClick={() => {
                            handleSubmit({ callback: routerGo });
                        }}
                    >
                        薪资确认
                    </Button>
                </div>
            );
        }
        if (isSecond && resultType === COMMUNICATE_RESULT_ENUM.OUT) {
            return (
                <div className={styles.buttonWrapper}>
                    <Button onClick={handleCancel}>取消</Button>
                    {saveButton}
                    <Button
                        {...buttonProps}
                        onClick={() => {
                            handleSubmit({
                                callback: () => {
                                    // history.push({
                                    //     pathname: '/office/personnelManagement/recruitment/candidate/notice',
                                    //     query: { candidateId, noticeType: NOTICE_TYPE.TERMINATE }
                                    // });
                                    routerGo();
                                }
                            });
                        }}
                    >
                        确认
                    </Button>
                </div>
            );
        }
        // 要求去掉沟通结果的默认值，只能先放两个按钮出来。
        return (
            <div className={styles.buttonWrapper}>
                <Button onClick={handleCancel}>取消</Button>
                {saveButton}
            </div>
        );
    };
    return (
        <Row>
            <Col span={3}></Col>
            <Col span={21}>{renderButton()}</Col>
        </Row>
    );
}

export default React.memo(Action);
